﻿using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Collections.Specialized;
using System.ComponentModel;
using System.Linq;
using System.Net;
using System.IO;
using Com.CodePlex.SPC3.SPbAM.Data;
using Com.CodePlex.SPC3.SPbAM.Controller;
using Com.CodePlex.SPC3.SPbAM.Model;
using System.Windows.Input;
using System.Text;
using System.Text.RegularExpressions;
//using Com.CodePlex.SPC3.SPbAM.View; //should not reference this http://social.msdn.microsoft.com/Forums/is/wpf/thread/3bced3ea-4a97-4456-bfe5-828289bcf971

namespace Com.CodePlex.SPC3.SPbAM.ViewModel {

    public class ActionViewModel : ViewModel {

        private ServerViewModel parent;
        private string path;
        private string action;

        public ActionViewModel(string path, ServerViewModel parent) {
            if (path == null) {
                throw new ArgumentNullException("path");
            }
            if (parent == null) {
                throw new ArgumentNullException("parent");
            }
            this.path = path;
            action = path.Substring(path.IndexOf(@"\actions\") + 9);
            action = action.Substring(0, action.IndexOf("."));
            this.parent = parent;
            DisplayName = Path.GetFileNameWithoutExtension(path);
            Mediator.Register(this);
            //note: lazy load: dont do more stuff here
        }

        #region Commands

        private ICommand runcommand;
        public ICommand RunCommand { get { return runcommand ?? (runcommand = new RelayCommand(param => Run())); } }

        private IEnumerable<CommandViewModel> treecommands;
        public IEnumerable<CommandViewModel> TreeCommands {
            get {
                if (treecommands == null) {
                    treecommands = new List<CommandViewModel>() {
						new CommandViewModel("Run", RunCommand)
					};
                }
                return treecommands;
            }
        }

        #endregion

        #region Display Properties

        private bool isselected;
        public bool IsSelected {
            get { return isselected; }
            set {
                if (value != isselected) {
                    isselected = value;
                    OnPropertyChanged(() => IsSelected);
                }
            }
        }

        public string ImageSource {
            get { return "pack://application:,,,/Resources/Images/RedDot.jpg"; }
        }

        #endregion

        public void Run() {
            //Mediator.Notify<LogMessage>(LogMessage.Log, new LogMessage { Object = parent.Workspace });
            parent.Workspace.AppendLog("Run: " + path);

            IList<CommandParameterWithType> paras = Automation.GetScriptParameters(path);

            CommandParameterWithType para = paras.SingleOrDefault(i => i.Name == "computername");
            if (para == null) {
                paras.Add(new CommandParameterWithType() { IsReadOnly = true, Type = "string", Name = "computername", Value = parent.Server.Name });
            } else {
                para.Value = parent.Server.Name;
            }
            para = paras.SingleOrDefault(i => i.Name == "username");
            if (para == null) {
                paras.Add(new CommandParameterWithType() { IsReadOnly = true, Type = "string", Name = "username", Value = "" });
            } else {
                para.Value = "";
            }
            para = paras.SingleOrDefault(i => i.Name == "password");
            if (para == null) {
                paras.Add(new CommandParameterWithType() { IsReadOnly = true, Type = "string", Name = "password", Value = "" });
            } else {
                para.Value = "";
            }

            //todo: merge with values from server

            Service.CommandParameterDialogResult result = new Service.CommandParameterDialogService().Show(paras);
            if (result.IsValid) {

                //todo: maybe launch a tab in a nested tab with the powerscript results???

                ServerRepository serverrepository = new ServerRepository();
                serverrepository.Load(parent.Server);
                AutomationResult aresult = Automation.RunPowerShellScript(parent.Server.Name, path, result.Values);
                if (aresult.Errors.Count > 0) {
                    aresult.Errors.ForEach(i => {
                        parent.Workspace.AppendLog(i);
                    });
                } else {
                    aresult.Results.ForEach(i => {
                        parent.Workspace.AppendLog(i);
                    });
                    parent.Server.AddActionResult(aresult.Results, action);
                    serverrepository.Save(parent.Server); //todo: write to a cache file instead
                }
            }
        }
    }
}